package main

import (
	"bufio"
	"fmt"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"

	"github.com/fatih/color"
	"github.com/gin-gonic/gin"
	"go-api-template/api/models/system"
	"go-api-template/api/models/tool"
	"go-api-template/api/router"
	"go-api-template/api/ws/front"
	"go-api-template/internal/util/codeUtil"
	"go-api-template/internal/util/systemUtil"
	"go-api-template/service"

	"go.uber.org/zap"
)

func main() {

	// 初始化配置
	service.Init()

	if service.Conf.App.Env == "prod" {
		gin.SetMode(gin.ReleaseMode)
	}

	// 消息中心
	go front.HUB.Run()

	// 初始化Model
	system.Init()
	tool.Init()

	// 刷新缓存日志
	defer func(Log *zap.Logger) {
		_ = Log.Sync()
	}(service.Log)

	// 关闭redis连接
	defer func() {
		if service.Conf.Redis.Enable {
			_ = service.Redis.Close()
		}
	}()

	// 运行服务
	runServer()
}

func runServer() {

	// 设置路由
	r := router.Init()

	oldPort := strconv.Itoa(service.Conf.App.Port)
	oldHttpsPort := service.Conf.App.SslPort

	// 运行HTTPS服务
	if service.Conf.App.SslPort != 0 {
		go func() {
			if !systemUtil.IsPortAvailable(service.Conf.App.SslPort) {
				newPort, _ := systemUtil.GetRandomAvailablePort()
				reader := bufio.NewReader(os.Stdin)
				fmt.Printf("HTTPS服务端口被占用，是否使用随机%s端口: y/n(default: y)\n", color.GreenString(strconv.Itoa(newPort)))
				fmt.Print("-> ")
				text, _ := reader.ReadString('\n')
				if text == "y" || text == "Y" || text == "" {
					service.Conf.App.SslPort = newPort
				} else {
					log.Fatalf("%v %s\n", color.RedString("HTTPS服务启动失败:"), fmt.Sprintf("%d端口被占用", oldHttpsPort))
				}
			}

			err := r.RunTLS(fmt.Sprintf(":%d", service.Conf.App.SslPort), service.Conf.App.SslCrt, service.Conf.App.SslKey)
			if err != nil {
				fmt.Printf("%v %s\n", color.RedString("HTTPS服务启动失败:"), err.Error())
			}
		}()
	}

	// HTTP强制跳转HTTPS
	if service.Conf.App.SslForce && service.Conf.App.SslPort != 0 {
		httpRouter := gin.Default()
		httpRouter.GET("/", func(c *gin.Context) {
			httpsURL := "https://" + service.Conf.App.Domain + fmt.Sprintf(":%d", service.Conf.App.SslPort) + c.Request.RequestURI
			fmt.Println("httpsURL: ", httpsURL)
			// 重定向到 HTTPS
			c.Redirect(http.StatusMovedPermanently, httpsURL)
		})
		if err := httpRouter.Run(fmt.Sprintf(":%d", service.Conf.App.Port)); err != nil {
			log.Fatalf("%v %s\n", color.RedString("HTTP服务启动失败:"), err.Error())
		}
	} else {
		if !systemUtil.IsPortAvailable(service.Conf.App.Port) {
			newPort, _ := systemUtil.GetRandomAvailablePort()
			reader := bufio.NewReader(os.Stdin)
			fmt.Printf("HTTP服务端口被占用，是否使用随机%s端口: y/n(default: y)\n", color.GreenString(strconv.Itoa(newPort)))
			fmt.Print("-> ")
			text, _ := reader.ReadString('\n')
			if text == "y" || text == "Y" || text == "" {
				service.Conf.App.Port = newPort
			} else {
				log.Fatalf("%v %s\n", color.RedString("HTTP服务启动失败:"), fmt.Sprintf("%s端口被占用", oldPort))
			}
		}
		fmt.Printf("%v %s\n", color.GreenString("HTTP访问地址:"), strings.ReplaceAll(service.Conf.App.Domain, oldPort, strconv.Itoa(service.Conf.App.Port)))

		err := r.Run(fmt.Sprintf(":%d", service.Conf.App.Port))
		if err != nil {
			log.Fatalf("%v %s\n", color.RedString("HTTP服务启动失败:"), err.Error())
		}

	}
}

func init() {
	code := codeUtil.GenerateSquirrelCode(`
SELECT IFNULL(mrttm.teachingTagId = '7821f4000ef311ecbf8800163e0ebd3a', 0) as 'is_required'
FROM mbl_resources_plan_workshop mrpw
         LEFT JOIN mbl_resources_teaching_tag_map mrttm on mrttm.oneWorkShopId = mrpw.planWorkshopId
         left join mbl_community_activity_camp mcac on mcac.planExtId = mrpw.planExtId
WHERE mrpw.oneExtId = ?
and mcac.activityId = ?

`)
	println(code)
}
